import {createStore,Commit} from 'vuex'
import axios,{AxiosRequestConfig} from 'axios'
import { testData,testPosts } from './testData'
export interface UserProps{
    isLogin:boolean,
    name?:string,
    id?:number,
    columnId?:number,
    avatar?:ImageProps
   
}
export interface ImageProps {
    id?: string;
    url?: string;
    createdAt?: string;
    fitUrl?: string;
  }
export interface PostProps {
    id: number;
    title: string;
    content:string,
    image?:string;
    createdAt?: string;
    columnId: number;
}
// 首页基本信息
export interface GlobalDataProps{
    error:GlobalErrorProps,
    token:string,
    loading:boolean,
    columns: { data:ColumnProps[]; currentPage: number; total: number };
    posts:PostProps[]
    user:UserProps
}
// 泛型：设置p默认是对象
export interface ResponseType<P = object>{
    code:number;
    msg:string;
    data:P
}
//错误提示组件类型
export interface GlobalErrorProps{
    status:boolean,
    message?:string
}
export interface ColumnProps {
    id: number;
    title: string;
    avatar?: ImageProps;
    description: string;
}
// 封装的方法
const getAndCommit=async(url:string,mutationName:string,commit:Commit)=>{
    const {data}=await axios.get(url)
    commit(mutationName,data)
    return data
}
// 封装的方法
const postAndCommit=async(url:string,mutationName:string,commit:Commit,payload:any)=>{
    const {data}=await axios.post(url,payload)
    commit(mutationName,data)
    //带promise的data,所以调用之后，用then可以获取到data的值
    return data  
}
const asyncAndCommit = async(url: string, mutationName: string, commit: Commit, config: AxiosRequestConfig = { method: 'get' }, extraData?: any) => {
    const { data } = await axios(url, config)
    if (extraData) {
      commit(mutationName, { data, extraData })
    } else {
      commit(mutationName, data)
    }
    return data
}
const store=createStore<GlobalDataProps>({
    state:{
        error:{status:false},
        token:localStorage.getItem('token') || '',
        loading:false,
        // columns:testData,
        columns: { data: [], currentPage: 0, total: 0 },
        posts:testPosts,
        user:{isLogin:false}
    },
    mutations:{
       createPost(state,newPost){
           state.posts.push(newPost)
       },
       fetchColumns(state,rawData){
           state.columns=rawData.data
       },
       fetchColumn(state,rawData){
          state.columns.data=rawData.data
       },
       fetchPosts(state,rawData){
           state.posts=rawData.data.list
       },
       setLoading(state,status){
            state.loading=status
       },
       setError(state,e:GlobalErrorProps){
         state.error=e
       },
       fetchCurrentUser(state,rawData){
           state.user={isLogin:true,...rawData.data}
       },
       login(state,rawData){
        // state.user={...state.user,isLogin:true,name:'老六',columnId:1}
        // console.log('qqqq',state.user)
        const {token}=rawData.data
        state.token=token
        localStorage.setItem('token',token)
        //设置请求头
        axios.defaults.headers.common.Authorization=`Bearer ${token}`
       },

       logout(state){
        state.token=''
        localStorage.removeItem('token')
        delete axios.defaults.headers.common.Authorization
       },
       updatePost(state, { data }) {
        state.posts=state.posts.map(post=>{
            if(post.id===data.id){
                return data
            }else{
                return post
            }
        })
      }
    },
    actions:{
        fetchColumns(context){
            // axios.get('/columns').then(resp=>{
            //     context.commit('fetchColumns',resp.data)
            // })

            // 封装出来的
            return getAndCommit('/columns','fetchColumns',context.commit)
        },
        fetchColumn({commit},cid){
            // axios.get(`/columns/${cid}`).then(resp=>{
            //     commit('fetchColumn',resp.data)
            // })

            return getAndCommit(`/columns/${cid}`,'fetchColumn',commit)
        },
        // async await
        async fetchPosts({commit},cid){
            // const {data}=await axios.get(`/columns/${cid}/posts`)
            // commit('fetchPosts',data)

            return getAndCommit(`/columns/${cid}/posts`,'fetchPosts',commit)
        },
        fetchCurrentUser({commit}){
           return getAndCommit('user/current','fetchCurrentUser',commit)
        },
        login({commit},payload){
            // payload是携带的参数
          return  postAndCommit('/user/login','login',commit,payload)
        },
        createPost({commit},payload){
            return postAndCommit('posts','createPost',commit,payload)
        },
        loginAndFetch({dispatch},loginData){
            return dispatch('login',loginData).then(()=>{
                return dispatch('fetchCurrentUser')
            })
        },
        updatePost({ commit }, { id, payload }) {
            return asyncAndCommit(`/posts/${id}`, 'updatePost', commit, {
              method: 'patch',
              data: payload
            })
        }
    },
    getters:{
        // biggerColumnLen(state){
        //     return state.columns.data.filter(c=>c.id>2).length
        // }
    }
})
export default store